Repository navigation
fix(tts): make Pocket TTS actually produce audio, and test that it does (#107) - #129
Merged
Merged
Conversation
Closes #107, which asked for a test that puts real text through the real sherpa-onnx + espeak-ng pipeline and asserts on the resulting audio. Writing that test found that Pocket TTS had never produced a single sample on Android. Three independent defects, each invisible to the existing tests: 1. JNI package mismatch. The vendored sherpa-onnx wrapper had been repackaged into xyz.libravault.core.tts.pocket.sherpa. Its `external fun`s are statically registered, so the runtime resolves them by a symbol derived from the fully-qualified class name, and the .so only exports Java_com_k2fsa_sherpa_onnx_*. Every native call failed with UnsatisfiedLinkError. Moved back to com.k2fsa.sherpa.onnx. 2. Kotlin 2.x lambda strategy vs. the streaming callback. sherpa-onnx looks up the specialized invoke([F)Ljava/lang/Integer; on the callback object, but Kotlin 2.x compiles lambdas via invokedynamic and D8 desugars those into synthetic classes carrying only the erased invoke(Object)Object. The lookup failed inside a native frame, aborting the process under CheckJNI. Replaced the lambda with an explicit SherpaGenerationCallback class. 3. Playback sample-rate mismatch. PocketPlayback hardcoded 24000 Hz - the rate of sherpa-onnx's own Pocket TTS model family - while the bundled LJSpeech Piper voice generates at 22050. Playback would have run ~8.8% fast and about a semitone and a half sharp. The rate is now a required parameter sourced from OfflineTts.sampleRate(). Also adds R8 keep rules for the vendored package. Verified by counterfactual: without them OfflineTtsVitsModelConfig is renamed to j5.g, which breaks the native GetFieldID lookups in release builds only. Testing: - PocketTtsAudioOutputTest (androidTest) runs the real pipeline through the same config the shipped engine uses and asserts on the PCM: non-silent, no NaNs, bounded silence, plausible duration, and - the stronger signals - that duration tracks text length and speech rate, and that different text yields different audio. All 10 pass on a Firebase Test Lab physical arm64 device (OP535DL1/API 34): 44 chars in 2.94s, and doubling the text gave exactly 2.00x the duration. - The AAR is arm64-v8a only, so the test self-skips on the x86_64 emulator ui-tests.yml uses. android-tts-audio-test.yml dispatches it to Test Lab. - PcmAnalysis measurement helpers are shared between the on-device test and new JVM tests against synthetic waveforms, so the thresholds keep CI signal between arm64 runs. - SherpaGenerationCallbackTest pins the JNI method descriptor on every push, where a Kotlin bump would first reintroduce defect 2. - Replaced a PocketPlaybackTest case that asserted a local variable against itself and never referenced PocketPlayback. Not covered: release-build R8 behaviour is verified via the mapping file, not by running the audio test on a minified APK - the instrumentation APK is debug and unminified. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Contributor
📱 iOS Build Status: PASSED✅ iOS Simulator Build & Unit Tests - success iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those. |
6 tasks
This was referenced Aug 18, 2026
github-actions Bot
added a commit
that referenced
this pull request
Aug 18, 2026
QA on PR #257 flagged that PocketTTSEngineTests.swift covered 3 of the 4 items in issue #256's Definition of Done, missing the sherpa-onnx C callback's retain/release contract - the highest-value part of the DoD given it's the exact boundary where Android's equivalent engine shipped 3 audio bugs (issue #107 / PR #129). Make `ttsCallback` and `PlaybackContext` internal (same "pure helpers should be internal" convention already used for pcmBuffer and the model-path constants), then call `ttsCallback` directly with a real, attached-but-unstarted `AVAudioPlayerNode`. Attach/connect are pure graph-configuration calls that touch no audio hardware or session - unlike `AVAudioEngine.start()`/`AVAudioSession.setActive(true)`, which are what actually caused the two ~30-minute CI hangs this file's XCTest guard exists to avoid - so this exercises the real `scheduleBuffer` call without approaching that boundary. New tests cover: a valid-samples call returns 1 and schedules a buffer; multiple simulated chunks against a single passRetained/ release pair (the actual usage shape in speak()) don't crash; and the nil-samples/zero-count/nil-arg guard branches don't dereference.
libravault-xyz
pushed a commit
that referenced
this pull request
Aug 19, 2026
…#257) * test(ios): cover PocketTTSEngine's pure logic behind the XCTest guard Extracts the model-path constants and pcmBuffer(from:format:) to internal (AGENTS.md's "pure helpers should be internal" convention) and reorders initialize() so the modelNotBundled check runs before the XCTest guard - no behaviour change for real usage, but it makes the missing-model error path reachable in tests instead of retired-by-guard. PocketTTSEngineTests.swift covers: the three model filenames pinned against setup-ios.sh/Android's PocketVoiceCatalog, modelNotBundled being thrown/not thrown depending on model presence, its errorDescription copy, and pcmBuffer's frame length / verbatim sample copy / empty-input handling. Deliberately out of scope: real audio output, and the sherpa-onnx C callback's retain/release lifecycle against a live AVAudioPlayerNode - both sit next to the exact AVAudioSession activation path that caused two ~30-minute CI timeouts before the guard existed, and this repo's dev agent has no local macOS to verify that boundary iteratively. Left as a known gap rather than guessed at. Closes #256 * test(ios): cover PocketTTSEngine's ttsCallback retain/release contract QA on PR #257 flagged that PocketTTSEngineTests.swift covered 3 of the 4 items in issue #256's Definition of Done, missing the sherpa-onnx C callback's retain/release contract - the highest-value part of the DoD given it's the exact boundary where Android's equivalent engine shipped 3 audio bugs (issue #107 / PR #129). Make `ttsCallback` and `PlaybackContext` internal (same "pure helpers should be internal" convention already used for pcmBuffer and the model-path constants), then call `ttsCallback` directly with a real, attached-but-unstarted `AVAudioPlayerNode`. Attach/connect are pure graph-configuration calls that touch no audio hardware or session - unlike `AVAudioEngine.start()`/`AVAudioSession.setActive(true)`, which are what actually caused the two ~30-minute CI hangs this file's XCTest guard exists to avoid - so this exercises the real `scheduleBuffer` call without approaching that boundary. New tests cover: a valid-samples call returns 1 and schedules a buffer; multiple simulated chunks against a single passRetained/ release pair (the actual usage shape in speak()) don't crash; and the nil-samples/zero-count/nil-arg guard branches don't dereference. --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #107. Also closes #131 ("Tapping Pocket TTS in Settings crashes app") — that crash is the same
UnsatisfiedLinkErrorfrom bug 1 below, escapinginitialize()'scatch (e: Exception)because it's anError; fixed both by the JNI package move and by widening that catch toThrowable.The issue asked for a test that runs the real sherpa-onnx + espeak-ng pipeline and asserts on the audio, since nothing in the repo did. Writing that test immediately found that Pocket TTS has never produced a single sample of audio on Android. Three independent defects, each invisible to the existing lifecycle/plumbing tests, a clean build, and a crash-free Robo run.
The three bugs
1. JNI package mismatch — nothing native ever resolved
Tts.ktwas vendored from upstream with its package changed toxyz.libravault.core.tts.pocket.sherpa. Itsexternal funs are statically registered JNI methods, resolved by a symbol derived from the fully-qualified class name. The.soexports:So every native call failed with
UnsatisfiedLinkError. Moved the file back tocom.k2fsa.sherpa.onnxwith a prominent do-not-move comment.This also hid behind a second problem:
initialize()caughtException, butUnsatisfiedLinkErroris anError, so it escaped the coroutine entirely instead of surfacing as a TTS error. Now catchesThrowable.2. Kotlin 2.x lambdas break the streaming callback
sherpa-onnx resolves the callback with
GetMethodID(cls, "invoke", "([F)Ljava/lang/Integer;")— the specialized invoke. Kotlin 1.x compiled lambdas to real classes carrying it, which is why upstream's sample works. Kotlin 2.x usesinvokedynamic, and D8 desugars those into$$ExternalSyntheticLambdaclasses implementing only the erasedinvoke(Object)Object:Raised inside a native frame, this aborts the process. Replaced with an explicit
SherpaGenerationCallbackclass; the emitted descriptor was verified withjavap.3. Playback sample-rate mismatch
PocketPlaybackhardcodedSAMPLE_RATE_HZ = 24000— the rate of sherpa-onnx's own Pocket TTS model family, not the bundled LJSpeech Piper voice, which generates at 22050. No resampling happens, so playback would have run ~8.8% fast and about a semitone and a half sharp. The rate is now a required parameter sourced fromOfflineTts.sampleRate().Bonus: R8 would have re-broken this in release
Release builds minify with no keep rule for the vendored package. Verified by counterfactual — removing the rule and re-running R8 renames
OfflineTtsVitsModelConfig -> j5.g, breaking the nativeGetFieldIDlookups. Debug builds aren't minified, so neither the new test nor manual debug testing would catch it.The test
PocketTtsAudioOutputTestruns the real pipeline through the samepocketTtsConfigthe shipped engine uses (extracted so the test can't drift from production) and asserts on the PCM.Assertions are aggregate and relative, not golden-waveform — ONNX output isn't bit-identical across devices and VITS samples from a noise distribution:
All 10 pass on a Firebase Test Lab physical arm64 device (OP535DL1 / API 34):
Where it runs
The AAR bundles arm64-v8a only, so the native library is simply absent on the x86_64 emulator
ui-tests.ymluses — the test self-skips there viaAssumerather than failing.android-tts-audio-test.yml(manual dispatch) sends it to a Test Lab physical device. Noteredfinis retired from Test Lab; the default is a current arm64 model.Keeping CI signal between arm64 runs
The arm64 test only runs on demand, so two JVM suites cover it on every push:
PcmAnalysisTest(24 tests) — the measurement math against synthetic waveforms, so a helper silently reporting "silent" for real speech can't turn the device test into one that never fails. The helpers live in atestSharedsource set compiled into both test source sets.SherpaGenerationCallbackTest— pins the JNI method descriptor, which is where a future Kotlin bump would first reintroduce bug 2.Also replaced a
PocketPlaybackTestcase that asserted a local variable against itself and never referencedPocketPlayback.Not covered
Release-build R8 behaviour is verified via the mapping file, not by running the audio test on a minified APK — the instrumentation APK is debug and unminified. Worth a follow-up if you want that guarded automatically.
🤖 Generated with Claude Code